package com.example.logindemo.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.logindemo.Pojo.Msg;
import com.example.logindemo.Pojo.User;
import com.example.logindemo.Service.UserService;
import com.example.logindemo.util.SmsComponent;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
public class LoginController {

    @Resource
    private UserService userService;

    @Autowired
    SmsComponent smsComponent;

    @Resource
    private RedisTemplate redisTemplate;


    @PostMapping("/LoginByUP")
    public Msg LoginByUP(@RequestBody User user){
        Subject subject = SecurityUtils.getSubject();
        if (user.getUserName() != null && userService.selectByUserName(user.getUserName())!=null
            && user.getPassWord() != null){
            AuthenticationToken token = new UsernamePasswordToken(user.getUserName(),user.getPassWord());
            try {
                subject.login(token);
                return Msg.success().add("User",userService.selectByUserName(user.getUserName()));

            } catch (AuthenticationException e) {

                return Msg.error().add("msg","服务器出现错误，请联系系统管理员！");
            }
        }else {
            return Msg.error().add("msg","用户名不存在！");
        }

    }

    @PostMapping("/getCode")
    public Msg sendCode(@RequestBody String json){
        JSONObject jsonObject = JSON.parseObject(json);
        String phone = jsonObject.getString("phone");
        String code = String.valueOf((int)((Math.random()*9+1)* Math.pow(10,6-1)));
        System.out.println(code);
        if (smsComponent.sendSmsCode(phone,code)){
            return Msg.success().add("code",code);
        }else
            return Msg.error().add("msg","服务器出现错误，请联系系统管理员！");

    }

    @PostMapping("/LoginByPhone")
    public Msg LoginByPhone(@RequestBody String json){
        JSONObject jsonObject = JSON.parseObject(json);
        if (redisTemplate.opsForValue().get(jsonObject.getString("phone")) !=null) {
            Subject subject = SecurityUtils.getSubject();
            AuthenticationToken token = new UsernamePasswordToken(jsonObject.getString("phone"),jsonObject.getString("code"));
            try {
                subject.login(token);
                return Msg.success().add("User",userService.selectByPhone(jsonObject.getString("phone")));
            } catch (AuthenticationException e) {
                return Msg.error().add("msg","服务器出现错误，请联系系统管理员！");
            }
        }else {
            return Msg.error().add("msg","请先获取验证码！");
        }


    }

    @PostMapping("/register")
    public Msg register(@RequestBody User user){
        if (userService.LoginByPhone(user.getPhone())){
            return Msg.error().add("msg","手机号已注册！");
        }else if (userService.LoginByUserName(user.getUserName())){
            return Msg.error().add("msg","用户名已注册！");
        }
        else {
            if(userService.addUser(user)){
                return Msg.success();
            }
            return Msg.error().add("msg","服务器出现错误，请联系系统管理员！");
        }

    }
    @RequiresRoles("admin")
    @PostMapping("/test")
    public Msg test(){
        return Msg.success();
    }
}
